﻿using System;
using System.IO;
using System.Windows.Forms;
using AccessControl.Utility.Security;


namespace AccessControl.Utility.ConnectionManager
{
    public class ConnectionStringManager
    {
        readonly string _path;
        private readonly string _fileName;
        public ConnectionStringManager(string fileName)
        {
            _path = Application.StartupPath;
            _fileName = fileName;
        }

        public string GetConnectionString()
        {
            var objConnectionString = new ConnectionString();

            try
            {
                objConnectionString.Connection = File.ReadAllText(String.Format("{0}\\{1}.dat", _path, _fileName));
                objConnectionString.Connection = new StringEncryption().DecryptString(objConnectionString.Connection);
            }
            catch (Exception)
            {
                objConnectionString = new ConnectionString();
            }
 
            return objConnectionString.Connection;
        }

        public void SetConnectionString(string connectionString)
        {
            try
            {

                connectionString = new StringEncryption().EncryptToString(connectionString);
                File.WriteAllText(String.Format("{0}.dat", _fileName), connectionString);
            }
            catch (Exception ex)
            {

                string message = "Failed to Write. Reason: " + ex.Message;
                throw new ApplicationException(message);
            }
        }
    }
}
